package com.drug.lib.view.recycptr;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

public class DynamicAdpTypePool implements AdapterTypePool {

    private @NonNull
    final List<Class<?>> mClass;
    private @NonNull
    final List<ItemViewBinder<?, ?>> mBinders;
    private @NonNull
    final List<Linker<?>> mLinkers;


    public DynamicAdpTypePool() {
        this.mClass = new ArrayList<>();
        this.mBinders = new ArrayList<>();
        this.mLinkers = new ArrayList<>();
    }

    public DynamicAdpTypePool(@NonNull List<Class<?>> classes, @NonNull List<ItemViewBinder<?, ?>> binders, @NonNull List<Linker<?>> linkers) {
        this.mClass = classes;
        this.mBinders = binders;
        this.mLinkers = linkers;
    }

    @Override
    public <T> void register(@NonNull Class<? extends T> clazz, @NonNull ItemViewBinder<T, ?> binder, @NonNull Linker<T> linker) {
        mClass.add(clazz);
        mBinders.add(binder);
        mLinkers.add(linker);
    }

    @Override
    public <T> void register(@NonNull Class<? extends T> clazz, @NonNull ItemViewBinder<T, ?> binder) {
        mClass.add(clazz);
        mBinders.add(binder);
        mLinkers.add(new DefaultLinker<T>());
    }

    @Override
    public boolean unregister(@NonNull Class<?> clazz) {
        boolean removed = false;
        while (true) {
            int index = mClass.indexOf(clazz);
            if (index != -1) {
                mClass.remove(index);
                mBinders.remove(index);
                removed = true;
            } else {
                break;
            }
        }
        return removed;
    }

    @Override
    public int size() {
        return mClass.size();
    }

    @Override
    public int firstIndexOf(@NonNull Class<?> clazz) {
        int index = mClass.indexOf(clazz);
        if (index != -1) {
            return index;
        }
        for (int i = 0; i < mClass.size(); i++) {
            if (mClass.get(i).isAssignableFrom(clazz)) {
                return i;
            }
        }
        return -1;
    }

    @NonNull
    @Override
    public ItemViewBinder<?, ?> getItemViewBinder(int index) {
        return mBinders.get(index);
    }

    @NonNull
    @Override
    public Class<?> getClass(int index) {
        return mClass.get(index);
    }

    @NonNull
    @Override
    public Linker<?> getLinker(int index) {
        return mLinkers.get(index);
    }
}
